<template>
  <div class="v-table-td-summary" @click="doEdit">
    <textarea
        v-if="editing"
        ref="textarea"
        v-model="summaryVal"
        @keydown.tab.prevent="onEnter"
        @keydown.enter.prevent="onEnter"
        @blur="endEdit"
        @focus="onFocus"
        class="v-table-td-summary-edit"
    ></textarea>
    <div class="p-8px h-full overflow-y" v-else>
      {{ summary }}
    </div>
  </div>
</template>
<script setup>

import {inject, nextTick, onMounted, ref, watch} from "vue";
import {trim} from "xe-utils";

const props = defineProps(['summary', 'rowIndex', 'detail']);
const textarea = ref(null)
const editing = ref(false)
const summaryVal = ref("")

const getNearSummary = inject('getNearSummary');
const updateFiled = inject('updateFiled');
const next = inject('next');

const doEdit = () => {
  editing.value = true;
  nextTick(() => {
    textarea.value.focus();
    textarea.value.select();
  })
}

const onFocus = () => {
  let summary = trim(getNearSummary(props.rowIndex));
  (summary && !trim(props.summary)) && updateFiled(props.rowIndex, 'summary', summary);
}

const endEdit = () => {
  editing.value = false;
  updateFiled(props.rowIndex, 'summary', summaryVal.value);
}

const onEnter = (e) => {
  editing.value = false;
  endEdit();
  next(props.rowIndex, 'subject');
}

watch(() => props.summary, (val) => {
  summaryVal.value = val;
})

onMounted(() => {
  summaryVal.value = props.summary;
})

defineExpose({
  doEdit,
  endEdit
})
</script>
<style scoped lang="less">
.v-table {

  &-td {
    &-summary {
      width: 210px;
      border-right: @border;

      &-edit {
        resize: none;
        outline: none;
        height: 100%;
        width: 100%;
        overflow: hidden;
        font-size: 12px;
        padding: 8px;

        &:focus {
          border: 1px solid @primary1-color;
        }
      }
    }
  }
}
</style>
